package com.coe3.handle;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import com.coe3.data.Information;
import com.coe3.data.PathManager;
import com.daydr3am.thenation.Store;
import com.daydr3am.thenation.TheNationMain;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;

public class NewsDownloadAsync extends AsyncTask<String, String, String>  {
	
	private Activity mActivity = null;
	private Store mStore = null;
	private static String mFileName = null;
	private Boolean mIsPDF;
	
	public NewsDownloadAsync( Activity activity, Store store, Boolean isPDF, String fileName) {
		this.mActivity = activity;
		this.mStore = store;
		this.mIsPDF = isPDF;
		setFileName(fileName);
	}
	
	@Override
    protected void onPreExecute() {
        super.onPreExecute();
        TheNationMain.getInstanceDownloadDialog(mActivity).show();
    }

	@SuppressLint("WorldReadableFiles")
	@Override
    protected String doInBackground( String... aurl ) {
        int count;

        try {
            URL url = new URL(aurl[0]);
            URLConnection conexion = url.openConnection();
            conexion.setConnectTimeout(90000);
            conexion.connect();

            int lenghtOfFile = conexion.getContentLength();

            if(getFileName() == null){
	            String[] separated = aurl[0].split("/");
	            setFileName(separated[separated.length-1]);
            }//end if
            
            PathManager.mkdir(mActivity, mIsPDF);
            InputStream input = new BufferedInputStream( url.openStream() );
            File file = new File(PathManager.getExternalCacheDir(mActivity, mIsPDF), getFileName());
            OutputStream output = new FileOutputStream(file);

            byte data[] = new byte[1024];

            long total = 0;
            
//            mStore.downloadDialog().setMax( lenghtOfFile );
            TheNationMain.getInstanceDownloadDialog(mActivity).setMax( lenghtOfFile );

            while ( ( count = input.read(data) ) != -1 ) {
                total += count;
                publishProgress( "" + total );
                output.write( data, 0, count );
            }

            output.flush();
            output.close();

            input.close();
        } catch (Exception e) {
        	e.printStackTrace();
        	Log.e(Information.TAG_DBUG, e.getMessage());
        }
        return null;
        
    }
	
	public static void setFileName(String filename) {
		mFileName = filename;
	}
	
	public static String getFileName() {
		return mFileName;
	}
    
	@Override
    protected void onPostExecute(String unused) {
		TheNationMain.dismissDownload(mActivity);
    	if(!mIsPDF)
    		mStore.onDownloadDidFinish( getFileName() );
    }
    
    @Override
    protected void onProgressUpdate(String... progress) {
        int total = Integer.parseInt(progress[0]);
        TheNationMain.getInstanceDownloadDialog(mActivity).setProgress(total);
    }
}
